package tms.presentation.bean.profile;

import tms.business.profile.ProfileService;
import tms.model.profile.UserProfileEntity;
import tms.util.constants.NavigationConstant;
import tms.util.constants.RequestParameter;
import tms.util.constants.UiMessage;
import tms.util.exception.ApplicationRuntimeException;
import tms.util.jabber.JabberManager;
import tms.util.jsf.FacesContextManager;
import tms.util.localization.LocalizationManager;
import tms.util.security.AppSecurityManager;

import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Named
@SessionScoped
public class ProfileViewBean implements Serializable {
    @Inject
    AppSecurityManager securityManager;
    @Inject
    FacesContextManager facesContextManager;
    @Inject
    LocalizationManager localizationManager;
    @EJB
    ProfileService profileService;

    private UserProfileEntity profile;
    private Boolean contentUpdated;
    private List<String> jabberStatuses;


    public UserProfileEntity getProfile() {
        if (profile == null) {
            profile = profileService.getProfile(securityManager.getUser().getProfileId());
        }
        return profile;
    }

    public Boolean getContentUpdated() {
        return contentUpdated;
    }

    public void updateProfile() {
        try {
            profileService.updateProfile(profile);
            facesContextManager.addMessage(localizationManager.localizedMessage(UiMessage.PROFILE_UPDATED));
            init();
        } catch (ApplicationRuntimeException e) {
            facesContextManager.addMessage(localizationManager.localizedMessage(e.getUiMessage()));
        }
    }

    public void cancel() {
        init();
        facesContextManager.navigateForOutcome(NavigationConstant.REDIRECT_TO_CURRENT_VIEW);
    }

    public void onContentUpdate() {
        contentUpdated = Boolean.TRUE;
    }

    public void cleanUp() {
        // check whether current request come from profilePage, if not clean up bean
        if (!"true".equals(facesContextManager.getRequestParameter(RequestParameter.PAGE_LOCAL_REQ))) {
            init();
        }
    }

    public List<String> getJabberUserStatuses() {
        if (jabberStatuses == null) {
            jabberStatuses = new ArrayList<String>();
            for (JabberManager.JabberUser.Status status : JabberManager.JabberUser.Status.values()) {
                jabberStatuses.add(status.name());
            }
            jabberStatuses.remove(JabberManager.JabberUser.Status.UNKNOWN.name());
        }
        return jabberStatuses;
    }
    

    private void init() {
        profile = null;
        contentUpdated = Boolean.FALSE;
    }
}
